package com.zh.springcloud.controller;

import com.zh.springcloud.common.Result;
import com.zh.springcloud.entity.Payment;
import com.zh.springcloud.service.PaymentService;
import com.zh.springcloud.utils.HttpRequestUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description:
 * @ClassName PaymentController
 * @date: 2021.06.08 15:50
 * @Author: zhanghang
 */
@RequestMapping("payment")
@RestController
@Slf4j
public class PaymentController {

	@Autowired
	private PaymentService paymentService;

	@Autowired
	private DiscoveryClient discoveryClient;

	@Value("${server.port}")
	private String serverPort;

	@PostMapping("save")
	@ApiOperation(value = "添加订单")
	public Result<?> savePayment(@RequestBody Payment payment){
		log.info("===========插入==========serverPort:"+serverPort);
		return paymentService.savePayment(payment);
	}

	@GetMapping("/{id}")
	@ApiOperation(value = "获取订单")
	public Result<?> getPaymentById(@PathVariable Long id){
		String clientIp = HttpRequestUtil.getClientIp();
		System.out.println("=======客户端ip:"+ clientIp);
		Result<Object> result = new Result<>();
		log.info("===========查询==========serverPort:"+serverPort);
		result.setResult(paymentService.getPaymentById(id));
		result.setMessage("springcloud with port:"+serverPort);
		return result;
	}

	@GetMapping("/port")
	public String getPort(){
		return serverPort;
	}

	@GetMapping("/feign/timeout")
	public String getPortTimeout(){
		try {
			Thread.sleep(3000);
		}catch (Exception e){

		}
		return serverPort;
	}

	@GetMapping("/discovery")
	@ApiOperation(value = "获取discoveryClient信息")
	public Result<?> getDiscoveryClient(){
		Result<Object> result = new Result<>();
		List<String> services = discoveryClient.getServices();
		for (String element : services){
			log.info("===========element======:"+element);
		}
		List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
		for (ServiceInstance instance : instances){
			log.info(instance.getInstanceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
		}
		result.setResult(discoveryClient);
		return result;
	}

	@GetMapping("/zipkin")
	public String paymentZipkin(){
		return "hi, i'am paymentzipkin server fall back,welcome to happy!";
	}

}
